package com.test.cordova.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.test.cordova.DownloadAIDL;
import com.test.cordova.NotifyCallBack;
import com.test.cordova.R;
import com.test.cordova.Student;
import com.test.cordova.util.Logger;
import com.test.cordova.util.StorageUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 使用aidl 双向通信 完成下载进度返回主线程
 */

public class DownloadService extends Service {

    private static final String TAG = DownloadService.class.getSimpleName();
   // private RemoteCallbackList<NotifyCallBack> notifyCallbacks = new RemoteCallbackList<>();
    private NotifyCallBack notifyCallBack ;
    private IBinder downBinder = new DownloadAIDL.Stub() {

        @Override
        public void startDownload() throws RemoteException {
            toDownLoad();
        }

        @Override
        public void registerProgressCallbck(NotifyCallBack callback) throws RemoteException {
            //notifyCallbacks.register(callback);
            notifyCallBack = callback;

        }

        @Override
        public void unRegisterProgressCallbck(NotifyCallBack callback) throws RemoteException {
            //notifyCallbacks.unregister(callback);
            notifyCallBack = null;
        }

        @Override
        public void handleStudent(Student student) throws RemoteException {
            Logger.e(TAG,student.toString());
        }
    };
    private OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(300, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(300,TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(50,TimeUnit.SECONDS)//设置连接超时时间
            .build();

    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private static final int NOTIFICATION_ID = 0;

    private NotificationManager mNotifyManager;
    private Notification.Builder mBuilder;

    public static boolean mIsDownloadOk = false;

    private void toDownLoad() {
        
       /* RequestBody formBody = new FormBody.Builder()
                .add("usernameFor4A", "")
                .add("timestamp", "")
                .add("sign", "")
                .add("location", "")
                .build();*/

        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                long bytetotal = response.body().contentLength();
                Log.i(TAG, "bytetotal " + bytetotal);
                long bytesum = 0;
                int byteread = 0;
                InputStream in = null;
                FileOutputStream out = null;
                try {
                    in = response.body().byteStream();
                    File dir = StorageUtil.getCacheDirectory(DownloadService.this);
                    String apkName = "WisdomCampD.apk";
                    File apkFile = new File(dir, apkName);
                    out = new FileOutputStream(apkFile);
                    byte[] buffer = new byte[BUFFER_SIZE];

                    int oldProgress = 0;

                    while ((byteread = in.read(buffer)) != -1) {

                        Log.i(TAG, "byteread：" + byteread + " bytesum：" + bytesum);
                        bytesum += byteread;
                        out.write(buffer, 0, byteread);

                        float tempFoat = ((float)bytesum) / ((float)bytetotal);
                        int progress = (int) (Float.valueOf(new DecimalFormat(".00").format(tempFoat)) * 100);

                        Log.i(TAG, "bytesum：" + bytesum + " bytetotal：" + bytetotal);
                        Log.i(TAG, "progress：" + progress + " oldProgress：" + oldProgress);

                        // 如果进度与之前进度相等，则不更新，如果更新太频繁，否则会造成界面卡顿
                        if (progress != oldProgress) {
                            updateDialog(progress);
                            updateProgress(progress);
                        }
                        oldProgress = progress;
                    }
                    // 下载完成
                    mIsDownloadOk = true;
                    installAPk(apkFile);

                    mNotifyManager.cancel(NOTIFICATION_ID);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "下载出错");
                    if (notifyCallBack != null) {
                        try {
                            notifyCallBack.notifyMainThreadProgress(-1);
                        } catch (RemoteException e1) {
                            e1.printStackTrace();
                        }
                    }
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException ignored) {
                            ignored.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException ignored) {
                            ignored.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    private void updateProgress(int progress) {

        //"正在下载:" + progress + "%"
        Log.i(TAG, progress + "");
        mBuilder.setContentText(this.getString(R.string.android_auto_update_download_progress, progress)).setProgress(100, progress, false);
        //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
    }


    private void installAPk(File apkFile) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
        try {
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException ignored) {
        }
        Log.i(TAG, "Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT + " Build.VERSION_CODES.N:" + Build.VERSION_CODES.N + " apkFile:" + apkFile.getAbsolutePath());
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, "com.vector_svg.cordova.provider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);

    }

    private void updateDialog(int pg) {
     /*  int len = notifyCallbacks.getRegisteredCallbackCount();
        for (int i = 0; i < len ; i++) {
            try {
                notifyCallbacks.getBroadcastItem(i).notifyMainThreadProgress(pg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }*/
       // notifyCallbacks.finishBroadcast();
        if (notifyCallBack != null) {
            try {
                notifyCallBack.notifyMainThreadProgress(pg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    private String url;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new Notification.Builder(this);
        mBuilder.setOngoing(true);

        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;

        mBuilder.setContentTitle(appName).setSmallIcon(icon);
        url = intent.getStringExtra("url");
        return downBinder;
    }

    @Override
    public void onDestroy() {
        //销毁回调资源 否则要内存泄露
       // notifyCallbacks.kill();
        super.onDestroy();
    }


}
